package com.shemy.sshiro.realm;

import com.shemy.sshiro.domain.SysMenu;
import com.shemy.sshiro.domain.SysRole;
import com.shemy.sshiro.domain.SysUser;
import com.shemy.sshiro.service.SysMenuService;
import com.shemy.sshiro.service.SysRoleService;
import com.shemy.sshiro.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description
 * @Author Dzsom
 * @Date 2019-05-13 16:53
 * @Encoding UTF-8
 * @Version 1.0
 **/
@Component
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;
    
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = (String) principalCollection.getPrimaryPrincipal();
        SysUser user=sysUserService.findByName(name);
        List<SysRole> roles = sysRoleService.findByUserId(user.getUserId());
        List<SysMenu> permissions = sysMenuService.findAllByRoles(roles);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (SysRole role:roles){
            simpleAuthorizationInfo.addRole(role.getRoleName());
        }
        for (SysMenu permission : permissions) {
            simpleAuthorizationInfo.addStringPermission(permission.getMenuName());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken.getPrincipal()==null){
            return null;
        }
        String name = authenticationToken.getPrincipal().toString();
        SysUser user = sysUserService.findByName(name);
        if (name==null){
            return null;
        }else {
            return new SimpleAuthenticationInfo(name, user.getPassword(), getName());
        }
    }
}
